package com.example.administrator.caigou51.activity;

import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.example.administrator.caigou51.EventBusClass.GotoFragment;
import com.example.administrator.caigou51.EventBusClass.JpushGoToMessage;
import com.example.administrator.caigou51.EventBusClass.UpdateShopCarRedCount;
import com.example.administrator.caigou51.R;
import com.example.administrator.caigou51.adapter.MainFragmentAdapter;
import com.example.administrator.caigou51.bean.CollectBean;
import com.example.administrator.caigou51.control.ChangeTextIcon;
import com.example.administrator.caigou51.fragment.MainFragment;
import com.example.administrator.caigou51.fragment.ShopCarFragment;
import com.example.administrator.caigou51.fragment.SortFragment;
import com.example.administrator.caigou51.fragment.UserCenterFragment;
import com.example.administrator.caigou51.global.App;
import com.example.administrator.caigou51.global.Constant;
import com.example.administrator.caigou51.global.NotifyUnReadMsg;
import com.example.administrator.caigou51.request.BaseResponse;
import com.example.administrator.caigou51.request.ICallBackForRequestServer;
import com.example.administrator.caigou51.request.RequestServerManager;
import com.umeng.update.UmengUpdateAgent;

import java.util.ArrayList;
import java.util.List;

import cn.xiaoneng.uiapi.Ntalker;
import cn.xiaoneng.uiapi.XNSDKListener;
import de.greenrobot.event.EventBus;

public class MainActivity extends GBaseActivity implements XNSDKListener {
    public static final int TAB_ShouYe = 0;
    public static final int TAB_FenLei = 1;
    public static final int TAB_GouWuChe = 2;
    public static final int TAB_GenRenZhongXin = 3;
    private android.support.v4.view.ViewPager viewPager_viewpager;
    //    private RadioButton radioButton_main_shopping;
//    private RadioButton radioButton_main_hospital;
//    private RadioButton radioButton_main_buyOverseas;
//    private RadioButton radioButton_main_userAbout;
    private ArrayList<Fragment> list;
    private MainFragmentAdapter fragmentAdapter;
    private long exitTime;
    private ImageView imageViewMain;
    private  boolean isShowImageMain=true;
/*    private ChangeTextIcon textIcon1;
    private ChangeTextIcon textIcon2;
    private ChangeTextIcon textIcon3;
    private ChangeTextIcon textIcon4;
    private ChangeTextIcon textIcon5;*/
   // private ArrayList<ChangeTextIcon> textIcons;
    private Ringtone ringtonenotification;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

      //  UmengUpdateAgent.update(this);
        setContentViewFor720_1280(R.layout.activity_main);
        initView();
        initFragment();
        addListener();

        //TaskGetPhoneNum();
        //初始化小能接口回调
        String siteid = "9704";//企业siteid
        String sdkKey = "39E97583-B6C1-49A6-9BF1-C960045BC5DA";//
        int initSDK = 0;
        //初始化小能客服SDK
        initSDK= Ntalker.getInstance().initSDK(getApplicationContext(), siteid, sdkKey);
        Uri notification = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.msgnotifyvoice);
        ringtonenotification = RingtoneManager.getRingtone(this, notification);
    //    EventBus.getDefault().register(this);
        Ntalker.getInstance().setSDKListener(this);

        if (0 == initSDK) {
            Log.e("initSDK", "初始化SDK成功");
        } else {
            Log.e("initSDK", "初始化SDK失败，错误码:" + initSDK);
        }
        if (App.getUserBean()!=null) {
            TaskGetCollectData(false);
        }

    }

    public static void TaskGetCollectData(final boolean isloadmore) {
        RequestServerManager.getInstanceDIY().handleMethodDIY(null, null, isloadmore, null,
                Constant.getRootUrl() + Constant.Action.Action_Collect, Constant.Action.Action_Collect, RequestServerManager.getInstanceDIY().
                        getRequestParams(Constant.Action.Action_Collect, App.getUserBean().getUserid(),App.getUserBean().getSession_id()), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        // JSONObject jsonObject = (JSONObject) result.getData();
                        List<CollectBean> collectBeanList = JSON.parseArray(result.getData().toString(), CollectBean.class);
                        App.saveCollectBeanListServer(collectBeanList);
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {

                    }
                });
    }
    public void onEventMainThread(GotoFragment gotoFragment) {
        resetOtherTabIcons();

        viewPager_viewpager.setCurrentItem(gotoFragment.getIndex(), false);

        if (gotoFragment.getIndex()==TAB_GouWuChe || gotoFragment.getIndex()==TAB_GenRenZhongXin) {
            textIcons.get(gotoFragment.getIndex()+1).setIconAlpha(1);
        }else
        {
            textIcons.get(gotoFragment.getIndex()).setIconAlpha(1);
        }
    }
    public void onEventMainThread(JpushGoToMessage jpushGoToMessage) {


        Intent i = new Intent(this, MessageActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //  i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
        startActivity(i);
    }
    public void onEventMainThread(UpdateShopCarRedCount updateShopCarRedCount) {

        updateBottomShopCarCount();
    }

    void initView() {
        EventBus.getDefault().register(this);
        getTopBar().setVisibility(View.GONE);

        getBottomBar().setVisibility(View.GONE);
        viewPager_viewpager = (android.support.v4.view.ViewPager) findViewById(R.id.viewPager_viewpager);
        imageViewMain= (ImageView) findViewById(R.id.imageViewMain);
        if (isShowImageMain) {
            imageViewMain.setVisibility(View.VISIBLE);
            imageViewMain.postDelayed(new Runnable() {
                @Override
                public void run() {
                    imageViewMain.setVisibility(View.GONE);
                    getBottomBarToShow(MainActivity.TAB_ShouYe);
                }
            },2000);
            isShowImageMain=false;
        }
//        radioButton_main_shopping = (RadioButton) findViewById(R.id.radioButton_main_shopping);
//        radioButton_main_hospital = (RadioButton) findViewById(R.id.radioButton_main_hospital);
//        radioButton_main_buyOverseas = (RadioButton) findViewById(R.id.radioButton_main_buyOverseas);
//        radioButton_main_userAbout = (RadioButton) findViewById(R.id.radioButton_main_userAbout);
   /*     textIcon1 = (ChangeTextIcon) findViewById(R.id.textIcon1);
        textIcon2 = (ChangeTextIcon) findViewById(R.id.textIcon2);
        textIcon3 = (ChangeTextIcon) findViewById(R.id.textIcon3);
        textIcon4 = (ChangeTextIcon) findViewById(R.id.textIcon4);
        textIcon5 = (ChangeTextIcon) findViewById(R.id.textIcon5);
        textIcons = new ArrayList<ChangeTextIcon>();
        textIcons.add(textIcon1);
        textIcons.add(textIcon2);
        textIcons.add(textIcon3);
        textIcons.add(textIcon4);
        textIcons.add(textIcon5);*/
    }

    void initFragment() {
        list = new ArrayList<Fragment>();
        list.add(new MainFragment());
        list.add(new SortFragment());
        list.add(new ShopCarFragment());
        // list.add(new HospitalFragment());
        // list.add(new UserAboutFragment());
        list.add(new UserCenterFragment());
        fragmentAdapter = new MainFragmentAdapter(this.getSupportFragmentManager(), list);
        viewPager_viewpager.setAdapter(fragmentAdapter);
        viewPager_viewpager.setOffscreenPageLimit(4);
    }

    void addListener() {
//        radioButton_main_shopping.setOnClickListener(this);
//        radioButton_main_buyOverseas.setOnClickListener(this);
//        radioButton_main_hospital.setOnClickListener(this);
//        radioButton_main_userAbout.setOnClickListener(this);
/*        textIcon1.setIconAlpha(1);
        textIcon1.setOnClickListener(this);
        textIcon2.setOnClickListener(this);
        textIcon3.setOnClickListener(this);
        textIcon4.setOnClickListener(this);
        textIcon5.setOnClickListener(this);*/
        viewPager_viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                //根据页面的偏移量设置渐变效果
                if (positionOffset > 0) {
                    if (position==MainActivity.TAB_GouWuChe || position==MainActivity.TAB_GenRenZhongXin) {
                        textIcons.get(position+1).setIconAlpha(1 - positionOffset);
                        textIcons.get(position + 2).setIconAlpha(positionOffset);
                    }else
                    {
                        textIcons.get(position).setIconAlpha(1 - positionOffset);
                        textIcons.get(position + 1).setIconAlpha(positionOffset);
                    }

                }
            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < textIcons.size(); i++) {
                    textIcons.get(i).setIconAlpha(0);
                }
                if (position==MainActivity.TAB_GouWuChe || position==MainActivity.TAB_GenRenZhongXin) {
                    textIcons.get(position+1).setIconAlpha(1);
                }else
                {
                    textIcons.get(position).setIconAlpha(1);
                }

//                switch (position) {
//                    case TAB_SHOPPING:
//                        //radioButton_main_shopping.setChecked(true);
//                        break;
//                    case TAB_HOSPITAL:
//                        //radioButton_main_hospital.setChecked(true);
//                        break;
//                    case TAB_BUY_OVERSEAS:
//                        ///radioButton_main_buyOverseas.setChecked(true);
//                        break;
//                    case TAB_USER_ABOUT:
//                        //radioButton_main_userAbout.setChecked(true);
//                        break;
//                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    @Override
    public void onClick(View v) {
        resetOtherTabIcons();
        super.onClick(v);


        switch (v.getId()) {
//            case R.id.radioButton_main_shopping:
//                viewPager_viewpager.setCurrentItem(TAB_SHOPPING, false);
//                break;
//            case R.id.radioButton_main_hospital:
//                viewPager_viewpager.setCurrentItem(TAB_HOSPITAL, false);
//                break;
//            case R.id.radioButton_main_buyOverseas:
//                viewPager_viewpager.setCurrentItem(TAB_BUY_OVERSEAS, false);
//                break;
//            case R.id.radioButton_main_userAbout:
//                viewPager_viewpager.setCurrentItem(TAB_USER_ABOUT, false);
//                break;
          /*  case R.id.textIcon1:
                viewPager_viewpager.setCurrentItem(TAB_ShouYe, false);
                textIcons.get(TAB_ShouYe).setIconAlpha(1);
                break;
            case R.id.textIcon2:
                viewPager_viewpager.setCurrentItem(TAB_FenLei, false);
                textIcons.get(TAB_FenLei).setIconAlpha(1);
                break;
            case R.id.textIcon3:
                viewPager_viewpager.setCurrentItem(TAB_WenZheng, false);
                textIcons.get(TAB_WenZheng).setIconAlpha(1);
                break;
            case R.id.textIcon4:
                viewPager_viewpager.setCurrentItem(TAB_GouWuChe, false);
                textIcons.get(TAB_GouWuChe).setIconAlpha(1);
                break;
            case R.id.textIcon5:
                viewPager_viewpager.setCurrentItem(TAB_GenRenZhongXin, false);
                textIcons.get(TAB_GenRenZhongXin).setIconAlpha(1);
                break;*/
        }
    }







    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //resetOtherTabIcons();
       // viewPager_viewpager.setCurrentItem(TAB_ShouYe, false);
        //textIcons.get(TAB_ShouYe).setIconAlpha(1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
       /* if (requestCode == TAB_ShouYe && resultCode == RESULT_OK)
            fragmentAdapter.getItem(TAB_ShouYe).onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2)
            fragmentAdapter.getItem(2).onActivityResult(requestCode, resultCode, data);
        if (requestCode == 3)
            fragmentAdapter.getItem(1).onActivityResult(requestCode, resultCode, data);
        if (requestCode == 4)
            fragmentAdapter.getItem(3).onActivityResult(requestCode, resultCode, data);
        if (requestCode == 5 && resultCode == RESULT_OK)
            fragmentAdapter.getItem(3).onActivityResult(requestCode, resultCode, data);*/
    }

    private void resetOtherTabIcons() {
        for (int i = 0; i < textIcons.size(); i++) {
            textIcons.get(i).setIconAlpha(0);
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
/*    public void onEventMainThread(UpdateFragment updateFragment) {
       // viewPager_viewpager.setCurrentItem(updateFragment.fragmentTag, false);
       // textIcons.get(updateFragment.fragmentTag).setIconAlpha(1);
    }*/
    //以下是小能接口回调

    @Override
    public void onChatMsg(boolean isSelfMsg, String settingid,
                          String setingname, String username, String msgcontent, long msgtime) {

        if (ringtonenotification == null)
            return;

        if (isSelfMsg == false)
            ringtonenotification.play();

    }

    @Override
    public void onUnReadMsg(final String settingid, final String settingname,
                            String username, String msgcontent, final int messagecount) {
        if (messagecount>0) {
            String unreadmsgstr = settingname + "发来" + messagecount
                    + "条消息哦！";
/*        NotifyUnReadMsg.getInstance(getApplicationContext())
                .setNotiType(R.drawable.visitor, "小能客服", unreadmsgstr,
                        ChatActivity.class);*/
            NotifyUnReadMsg.getInstance(getApplicationContext()).setNotiToChat(R.drawable.visitor, "小能客服", unreadmsgstr,
                    ChatActivityEmpty.class, settingid, settingname, username, msgcontent, messagecount);
        }
    }

    @Override
    public void onClickMatchedStr(String s, String s1) {

    }
    //处理所有的聊天信息中被系统认定为email、电话号码、url的点击事件
    @Override
    public void onClickUrlorEmailorNumber(int i, String s) {

    }

    @Override
    public void onClickShowGoods(int i, int i1, String s, String s1, String s2, String s3, String s4, String s5) {

    }

    @Override
    public void onError(int i) {

    }
    //以上是小能接口回调
}

